<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/9/4
 * Time: 14:29
 */
namespace app\common;


use think\App;
use think\facade\Env;
use think\Log;

class MyLog
{
    protected static $log_id;

    public static function setLogId($log_id = '')
    {
        if(!empty($log_id)) self::$log_id = $log_id;
        if(empty(self::$log_id))
        {
            self::$log_id = md5(uniqid());
        }
        return self::$log_id;
    }

    /**
     * [日志log]
     * @param  [type] $mark        [备注、关键词]
     * @param  [type] $log_content [内容]
     * @param  string $file        [名]
     * @param  string $level        [级别 1=通知；2=警告]
     * @return [type]              [description]
     */
    protected static function writeLog($mark, $log_content, $file = "", $level = 1) {
        $max_size = 30000000;
        $root_path = Env::get('ROOT_PATH');
        $_level = '';
        if($level == 2) $_level = '_err';

        $log_filename = $root_path . '/logs/' . date('Ymd') . $_level . ".log";
        if ($file) $log_filename = $root_path . '/logs/' . date('Ymd') . '_' . $file . $_level . ".log";

        if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
            rename($log_filename, dirname($log_filename) . '/' . date('YmdH') . '_' . $file . $_level . ".log");
        }

        $t = microtime(true);
        $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
        $d = new \DateTime (date('Y-m-d H:i:s.' . $micro, $t));

        if(is_array($log_content)){
            $log_content = json_encode($log_content,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }

        file_put_contents($log_filename, '   ' . $d->format('Y-m-d H:i:s') . ' logId:' . self::$log_id . " key：" . $mark . "\r\n" . $log_content . "\r\n------------------------ --------------------------\r\n", FILE_APPEND);
    }

    /**
     * [信息日志log]
     * @param  [type] $mark        [备注、关键词]
     * @param  [type] $log_content [内容]
     * @param  string $file        [名]
     * @return [type]              [description]
     */
    public static function infoLog($mark, $log_content, $file = "",$log_id = '')
    {
        self::setLogId($log_id);
        self::writeLog($mark, $log_content, $file);
    }

    /**
     * [警告日志log]
     * @param  [type] $mark        [备注、关键词]
     * @param  [type] $log_content [内容]
     * @param  string $file        [名]
     * @return [type]              [description]
     */
    public static function errorLog($mark, $log_content, $file = "",$log_id = '')
    {
        self::setLogId($log_id);
        self::writeLog($mark, $log_content, $file, 2);
    }
}